import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';

import { VersioningType, ValidationPipe } from '@nestjs/common';
import * as session from 'express-session'; //回话验证
import * as cors from 'cors'; //跨域处理

import {
  ExpressAdapter,
  NestExpressApplication,
} from '@nestjs/platform-express'; //上传文件
import { join } from 'path';

import { middleWareAll } from './globalware/routingMiddleware'; //访问白明单
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Response } from './common/response';
import { HttpAbnormal } from './common/abnormal';
import { RoleGuard } from './guard/role/role.guard';

import * as http from 'http';
import * as https from 'https';
import * as express from 'express';

// import * as https from 'https';
import * as fs from 'fs';

// const keyFile = fs.readFileSync('/opt/txy-zs/jsgong.com.cn.key');
// const certFile = fs.readFileSync('/opt/txy-zs/jsgong.com.cn_bundle.pem');

import * as path from 'path';

// 获取证书文件的绝对路径
const sslCertPath = path.join(__dirname, 'certs', 'jsgong.com.cn_bundle.crt');
const privateKeyPath = path.join(__dirname, 'certs', 'jsgong.com.cn.key');

const keyFile = fs.readFileSync(privateKeyPath);

const certFile = fs.readFileSync(sslCertPath);

const credentials = { key: keyFile, cert: certFile };

async function bootstrap() {
  const server = express();
  // const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
  // const app = await NestFactory.create(AppModule);
  // NestExpressApplication 应用一些与Express相关的配置
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(server),
    {
      httpsOptions: credentials,
    },
  );
  const options = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('games接口文档')
    .setDescription('描述CURD')
    .setVersion('1')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/api-docs', app, document);

  app.enableVersioning({
    //RESTful 版本控制
    type: VersioningType.URI,
  });
  app.use(cors()); //跨域的解决
  app.use(middleWareAll); // 全局中间件
  app.useStaticAssets(join(__dirname, '../images'), {
    // useStaticAssets 是 Nest.js 中用于配置静态资源的方法
    //静态文件预览
    prefix: '/games',
  });
  app.use(
    session({
      secret: 'games',
      name: 'games.session',
      rolling: true,
      cookie: { maxAge: null },
    }),
  );
  app.useGlobalInterceptors(new Response()); //响应拦截器
  app.useGlobalFilters(new HttpAbnormal()); //异常拦截器
  app.useGlobalPipes(new ValidationPipe()); //注册全局DTO验证管道;全局优先自定义的
  // app.useGlobalGuards(new RoleGuard(new Reflector())); //全局守卫
  // await app.listen(3000);

  await app.init();
  http.createServer(server).listen(3000);
  https.createServer(credentials, server).listen(443, () => {
    console.log('server listening--443');
  });
}
bootstrap();
